//
//  LoginController.swift
//  SCA
//
//  Created by tjun on 2025/9/1.
//

import UIKit
import TTTAttributedLabel


enum LoginPageOperationType {
   case login
   case register
   case forgetPassword
}

class LoginController: BaseController {
    
    private var scrollView: UIScrollView!
    private var contentView: UIView!
    private let loginButton = SelectableButton()
    private let registerButton = SelectableButton()
    
    private let loginView = LoginView()
    private let registerView = RegisterView()
    private let forgetPasswordView = ForgetPasswordView()
    
    private var targetView: UIView!

    private var operationType: LoginPageOperationType = .login {
        didSet {
            if operationType == .login {
                
                loginView.isHidden = false
                registerView.isHidden = true
                forgetPasswordView.isHidden = true
                targetView = loginView
                
                loginButton.isSelected = true
                registerButton.isSelected = false

            } else if operationType == .register {
                
                registerView.isHidden = false
                loginView.isHidden = true
                forgetPasswordView.isHidden = true
                targetView = registerView
                registerButton.isSelected = true
                loginButton.isSelected = false

            } else if operationType == .forgetPassword {
                
                forgetPasswordView.isHidden = false
                loginView.isHidden = true
                registerView.isHidden = true
                targetView = forgetPasswordView
                registerButton.isSelected = false
                loginButton.isSelected = false
            }
            
            updateContentSize()
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        
        scrollView = UIScrollView(frame: CGRect(x: 0, y: 0, width: view.width, height: screenHeight)).addTo(view)
        scrollView.keyboardDismissMode = .onDrag
        scrollView.showsVerticalScrollIndicator = false
        scrollView.showsHorizontalScrollIndicator = false
        scrollView.alwaysBounceVertical = true
        scrollView.contentInsetAdjustmentBehavior = .never
        
        let contentSize = CGSize(width: scrollView.width, height: scrollView.height)
        
        scrollView.contentSize = contentSize
        
        contentView = UIView().addTo(scrollView)
        contentView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
            make.size.equalTo(contentSize)
        }
        
        let logoImageView = UIImageView(image: Assets.Image.loginLogo).addTo(contentView)
        logoImageView.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.top.equalTo(navBarHeight + 20)
        }
        
        loginButton.addTo(contentView)
        loginButton.setTitle("登入".localizedString, for: .normal)
        
        loginButton.normalFont = UIFontMake(16)
        loginButton.selectedFont = UIFontMediumMake(16)
        loginButton.addTarget(self, action: #selector(loginButtonTapped), for: .touchUpInside)
        loginButton.isSelected = true
        loginButton.snp.makeConstraints { make in
            make.left.equalTo(AppStyle.margin.left)
            make.height.equalTo(28)
            make.top.equalTo(logoImageView.snp.bottom).offset(30)
        }
        
        registerButton.addTo(contentView)
        registerButton.setTitle("注册".localizedString, for: .normal)
        registerButton.normalFont = UIFontMake(16)
        registerButton.selectedFont = UIFontMediumMake(16)
        registerButton.isSelected = false
        registerButton.addTarget(self, action: #selector(registerButtonTapped), for: .touchUpInside)
        registerButton.snp.makeConstraints { make in
            make.left.equalTo(loginButton.snp.right).offset(28)
            make.height.equalTo(28)
            make.top.equalTo(loginButton)
        }
        
        let languageButton = UIButton(image: Assets.Image.languageIcon, target: self, action: #selector(languageButtonTapped)).addTo(contentView)
        languageButton.snp.makeConstraints { make in
            make.right.equalTo(-26)
            make.centerY.equalTo(registerButton)
            make.height.width.equalTo(40)
        }
        
        let modeButton = UIButton(image: Assets.Image.styleMode, target: self, action: #selector(modeButtonTapped)).addTo(contentView)
        modeButton.snp.makeConstraints { make in
            make.right.equalTo(languageButton.snp.left).offset(-14)
            make.centerY.equalTo(registerButton)
            make.height.width.equalTo(40)
        }
        
        loginView.addTo(contentView)
        loginView.forgetPasswordButton.addTarget(self, action: #selector(forgetPasswordButtonTapped), for: .touchUpInside)
        loginView.onConfirmButtonTaped = { [weak self] in
            if let self = self {
                self.confirmButtonTaped()
            }
        }
        loginView.snp.makeConstraints { make in
            make.top.equalTo(loginButton.snp.bottom)
            make.left.right.equalToSuperview()
            make.bottom.equalTo(loginView.lastView).offset(20)
        }
        
        registerView.addTo(contentView)
        registerView.onConfirmButtonTaped = { [weak self] in
            if let self = self {
                self.confirmButtonTaped()
            }
        }
        registerView.snp.makeConstraints { make in
            make.top.equalTo(loginButton.snp.bottom)
            make.left.right.equalToSuperview()
            make.bottom.equalTo(registerView.lastView).offset(20)
        }
        
        forgetPasswordView.addTo(contentView)
        forgetPasswordView.onConfirmButtonTaped = { [weak self] in
            if let self = self {
                self.confirmButtonTaped()
            }
        }
        forgetPasswordView.snp.makeConstraints { make in
            make.top.equalTo(loginButton.snp.bottom)
            make.left.right.equalToSuperview()
            make.bottom.equalTo(forgetPasswordView.lastView).offset(20)
        }
        
        operationType = .login
    }
    
    @objc func modeButtonTapped() {
        ThemeManager.shared.toggleStyle()
    }
    
    @objc func languageButtonTapped() {
        let selectLanguageController = SelectLanguageController()
        present(selectLanguageController, animated: false)
    }

    private func confirmButtonTaped() {
        
        if operationType == .login {
            guard let username = loginView.usernameTextField.textField.text, let password = loginView.passwordTextField.textField.text else {
                return
            }
            
            HUD.showLoadingInView(self.view)
            MineService.login(username: username, password: password) {
                HUD.hideHUD()
            } failure: { error in
                printf("登录失败")
            }
            return
        }
        
        if operationType == .register {
            
            guard let username = registerView.usernameTextField.textField.text,
                  let password = registerView.passwordTextField.textField.text else {
                return
            }
            
            HUD.showLoadingInView(self.view)

            let referralCode = registerView.referralCodeTextField.textField.text
            MineService.register(referralCode: referralCode, username: username, password: password) {
                self.registerView.reset()
                IconMessageAlert(messsage: "成功创建账户".localizedString, iconType: .succeed).showIn(self)
            }
            return
        }
        
        if operationType == .forgetPassword {
            
            guard let username = forgetPasswordView.usernameTextField.textField.text,
                  let password = forgetPasswordView.passwordTextField.textField.text,
                  let otf = forgetPasswordView.otpTextField.textField.text else {
                return
            }
            
            HUD.showLoadingInView(self.view)
            MineService.forgetPassword(username: username, password: password, otf: otf) {
                HUD.showMessage("修改成功".localizedString)
                self.forgetPasswordView.reset()
                self.operationType = .login
            } failure: { error in
                
            }
            return
        }
        
    }
    
    @objc func forgetPasswordButtonTapped() {
        let forgetPasswordController = ForgetPasswordController()
        self.navigationController?.pushViewController(forgetPasswordController, animated: true)
//        return;
//        operationType = .forgetPassword
    }
    
    @objc func loginButtonTapped() {
        operationType = .login
    }
    
    @objc func registerButtonTapped() {
        operationType = .register
    }
    
    private func updateContentSize() {
        
        contentView.setNeedsLayout()
        contentView.layoutIfNeeded()
        
        let contentSize = CGSizeMake(view.width, targetView.maxY + 10 + tabBarSafeBottomMargin)
        scrollView.contentSize = contentSize
        contentView.snp.remakeConstraints { make in
            make.edges.equalToSuperview()
            make.size.equalTo(contentSize)
        }
    }
    
//    override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
//        super.traitCollectionDidChange(previousTraitCollection)
//
//        if traitCollection.hasDifferentColorAppearance(comparedTo: previousTraitCollection) {
//            // ⚡ 深浅色切换时会触发
//            printf("深浅色切换时会触发")
//        }
//    }
    
    override var hiddenNavigationBar: Bool {
        return true
    }
}

